package com.wogu.jwa.web.admin.model;

import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;

import com.wogu.jwa.classes.Model;

public class GroupModel extends Model {
	private static final String GROUP = "group";
	private static GroupModel instance = null;
	
	private static JCS groupCache;
	static {
		try {
			groupCache = JCS.getInstance(GROUP);
		} catch(CacheException e) {
			logger.error("unable to init groupCache", e);
		}
	}
	
	public GroupModel() {
		super(GROUP);
	}
	
	public Map<Integer, String> getGroups(String fields, String where, String[] whereData, String order, String limit) throws SQLException {
		ResultSet rs = select(fields, where, whereData, order, limit);
		HashMap<Integer, String> groups = new HashMap<>();
		while(rs.next()) {
			groups.put(rs.getInt("groupid"), rs.getString("groupname"));
		}
		rs.close();
		return groups;
	}
	
	public Map<Integer, String> getGroups() throws SQLException {
		return getGroups(null, null, null, null, null);
	}
	
	@SuppressWarnings("unchecked")
	public Map<Integer, String> getGroupsCache() throws SQLException, CacheException {
		HashMap<Integer, String> groups = (HashMap<Integer, String>) groupCache.get(GROUP);
		if(null == groups) {
			groups = (HashMap<Integer, String>)getGroups();
			groupCache.put(GROUP, groups);
		} 
		
		return groups;
	}
	
	public static GroupModel getInstance() {
		if(null == instance) {
			instance = new GroupModel();
		}
		
		return instance;
	}
	
	public Map<String, String> getGroup(String fields, String where, String[] whereData) throws SQLException {
		final ResultSet rs = select(fields, where, whereData, null, "0,1");
		if(!rs.next()) return null;
		HashMap<String, String> group = new HashMap<String, String>(){{
			put("groupid", rs.getString("groupid"));
			put("groupname", rs.getString("groupname"));
		}};
		rs.close();
		return group;
	}
	
	public int updateGroup(HashMap<String, String> data, String where, String[] whereData) throws SQLException {
		return update(data, where, whereData);
	}
	
	public int addGroup(Map<String, String> data) throws SQLException {
		return insert(data);
	}
}